﻿using DDDSample.Domain.Core.Bus;
using DDDSample.Domain.Core.Command;
using DDDSample.Domain.Interfaces;
using DDDSample.Domain.Notifications;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Text;

namespace DDDSample.Domain.CommandHandlers
{
    /// <summary>
    /// 领域命令处理程序
    /// 用来作为全部处理程序的基类，提供公共方法和接口数据
    /// </summary>
    public class CommandHandler
    {
        // 注入工作单元
        private readonly IUnitOfWork _uow;
        // 注入中介处理接口
        private readonly IMediatorHandler _bus;
        // 注入缓存，用来存储错误信息
        private IMemoryCache _cache;

        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="uow"></param>
        /// <param name="bus"></param>
        /// <param name="cache"></param>
        public CommandHandler(IUnitOfWork uow,IMediatorHandler bus,IMemoryCache cache)
        {
            _uow = uow;
            _bus = bus;
            _cache = cache;
        }

        // 将领域命令中的验证错误信息收集
        protected void NotifyValidationErrors(Command message)
        {
            List<string> errorInfo = new List<string>();
            foreach (var error in message.ValidationResult.Errors)
            {
                //errorInfo.Add(error.ErrorMessage);
                //将错误信息提交到事件总线，派发出去
                _bus.RaiseEvent(new DomainNotification("",error.ErrorMessage));
            }
            //将错误信息收集
            //_cache.Set("ErrorData",errorInfo);
        }

        /// <summary>
        /// 工作单元提交
        /// 下一步添加领域通知，用来通知错误
        /// </summary>
        /// <returns></returns>
        public bool Commit()
        {
            if (_uow.Commit())
                return true;
            return false;
        }
    }
}
